<template>
  <div class="header">
    菜单名：<el-input v-model="filterText" placeholder="请输入菜单名" style="width: 200px" />
    <el-button type="primary" @click="append()">新 增</el-button>
  </div>

  <el-tree
    ref="treeRef"
    :data="tableList"
    :props="defaultProps"
    default-expand-all
    :filter-node-method="filterNode"
  >
    <template #default="{ node, data }">
      <span class="custom-tree-node">
        <span>{{ node.label }}</span>
        <div class="btnBox">
          <a @click.stop="append(data)" link> 修改 </a>
          <el-button type="danger" @click.stop="remove(data)" link> 删除 </el-button>
        </div>
      </span>
    </template>
  </el-tree>
  <el-dialog
    v-model="dialogShow"
    :title="ruleForm.id ? '修改菜单' : '新增菜单'"
    class="DriverDetailDialog"
    width="25%"
    :close-on-click-modal="false"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="90px"
      class="demo-ruleForm"
    >
      <el-form-item label="菜单名称:" prop="name">
        <el-input v-model="ruleForm.name" />
      </el-form-item>
      <el-form-item label="类型:" prop="type">
        <el-select v-model="ruleForm.type" placeholder="请选择类型" style="width: 100%">
          <el-option label="菜单" value="1" />
          <el-option label="按钮" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="URL:" prop="url">
        <el-input v-model="ruleForm.url" />
      </el-form-item>
      <el-form-item
        label="标识符:"
        prop="code"
      >
        <el-input v-model="ruleForm.code" />
      </el-form-item>
      <el-form-item label="序列号:" prop="num">
        <el-input v-model="ruleForm.num" />
      </el-form-item>
      <el-form-item label="图标:" prop="icon">
        <el-input v-model="ruleForm.icon" />
      </el-form-item>
      <el-form-item label="上级菜单:" prop="parentId">
        <el-cascader
          :options="tableList"
          v-model="ruleForm.parentId"
          :props="cascaderProps"
          placeholder="不选择即为顶层菜单"
          clearable
          style="width: 100%"
        />
      </el-form-item>
    </el-form>
    <footer>
      <el-button type="primary" style="width: 80px" @click="addMenu(ruleFormRef)">确 定</el-button>
      <el-button style="width: 80px" @click="dialogShow = false">取 消</el-button>
    </footer>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, toRaw, watch } from 'vue'
import { menuGroupAll, insert, deleteById,updateById } from '@/api/apis/user'
import { ElMessage, ElTree } from 'element-plus'
import { store } from '@/store'
import { ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

import dayjs from 'dayjs'
const treeRef = ref<InstanceType<typeof ElTree>>()

//表格数据
const tableList = ref([])
//加载
const loading = ref(false)
const filterText = ref('')
watch(filterText, (val) => {
  treeRef.value!.filter(val)
})

const defaultProps = {
  children: 'childMenuList',
  label: 'name',
}

const cascaderProps = {
  children: 'childMenuList',
  label: 'name',
  value: 'id',
  checkStrictly: true,
  emitPath: false,
}

const ruleForm = reactive({
  name: '',
  type: '1',
  url: '',
  code: '',
  num: '',
  parentId: '',
  icon: '',
  id: undefined,
})
let _form = toRaw({
  ...ruleForm,
})
const rules = reactive<any>({
  name: [
    {
      required: true,
      message: '请输入菜单名字',
      trigger: 'blur',
    },
  ],
  type: [
    {
      required: true,
      message: '请选择菜单类型',
      trigger: 'change',
    },
  ],
  url: [
    {
      required: true,
      message: '请输入url',
      trigger: 'blur',
    },
  ],
  code: [
    {
      required: true,
      message: '请输入标识符',
      trigger: 'blur',
    },
  ],
  num: [
    {
      required: true,
      message: '请输入排序',
      trigger: 'blur',
    },
  ],
})
const filterNode = (value: string, data: any) => {
  if (!value) return true

  return data.name.includes(value)
}

onMounted(() => {
  getTableList()
})
//获取表格数据
const getTableList = async () => {
  loading.value = true
  let { data } = await menuGroupAll()
  tableList.value = data.data
  loading.value = false
}

const dialogShow = ref(false)

const append = (data?: any) => {
  if (data) {
    ruleForm.name = data.name
    ruleForm.type = data.type
    ruleForm.url = data.url
    ruleForm.code = data.code
    ruleForm.num = data.num
    ruleForm.parentId = data.parentId
    ruleForm.icon = data.icon
    ruleForm.id = data.id
  } else {
    Object.assign(ruleForm, _form)
  }

  dialogShow.value = true
}

const remove = (val: any) => {
  ElMessageBox.confirm('是否删除该菜单?', '操作确认', {
    type: 'warning',
  })
    .then(async () => {
      let { data } = await deleteById(val.id)
      if (data.code == 200) {
        ElMessage.success('删除成功')
        getTableList()
      } else {
        ElMessage.error(data.message)
      }
    })
    .catch(() => {})
}

let storeData = store()
const userInfo = storeData.getUserInfo()
const ruleFormRef = ref<FormInstance>()
const addMenu = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      addMenuApi()
    } else {
      console.log('error submit!', fields)
    }
  })
}
const addMenuApi = async () => {
  interface IObj{
    deleted:number|string,
    parentId:string,
    updateId?:string,
    updateTime?:string,
    createId?:string,
    createTime?:string,
  }
  let obj:IObj = {
    deleted: 1,
    parentId: ruleForm.parentId || '0',
  }
  let res
  if (ruleForm.id) {
    obj.updateId=userInfo.id
    obj.updateTime=dayjs().format('YYYY-MM-DD HH:mm:ss') 

    res = await updateById({ ...ruleForm, ...obj })
  }else{
    obj.createId=userInfo.id
    obj.createTime=dayjs().format('YYYY-MM-DD HH:mm:ss')
    res = await insert({ ...ruleForm, ...obj })
  }
  if (res.data.code == 200) {
    ElMessage.success(ruleForm.id?'修改成功':'新增成功')
    dialogShow.value = false
    getTableList()
  } else {
    ElMessage.error(res.data.message)
  }
}
</script>
<style lang="scss">
.DriverDetailDialog {
  .el-dialog__body {
    padding-top: 5px;
  }
}
</style>
<style scoped lang="scss">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
footer {
  text-align: center;
}
.header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  button {
    margin-left: 10px;
  }
}
.btnBox {
  display: flex;
  align-items: center;
  a {
    margin-right: 10px;
  }
}
</style>
